import { Link } from '@brillout/docpress'

The `guard()` hook enables you to protect pages from unauthorized/unexpected access.

```js
// /pages/admin/+guard.js

import { render } from 'vike/abort'

// This guard() hook protects all pages /pages/admin/**/+Page.js

export async function guard(pageContext) {
  if (!pageContext.user.isAdmin) {
    throw render(401, "You aren't allowed to access this page.')
  }
}
```

Note that:

- It can be asynchronous. (Unlike Route Functions which are synchronous.)
- A single `guard()` hook <Link href="/config#inheritance">can apply to one or multiple pages</Link>.
- It's always used together with <Link href="/render" text={<code>throw render()</code>} /> or <Link href="/redirect" text={<code>throw redirect()</code>} />. The `guard()` hook doesn't accept any return value.


See also: <Link href="/auth#login-flow" />.



## TypeScript

```ts
export { guard }

import type { GuardAsync } from 'vike/types'
import { render } from 'vike/abort'

const guard: GuardAsync = async (pageContext): ReturnType<GuardAsync> => {
  // ...
}
```

## See also

- <Link href="/routing" />
- <Link href="/auth#login-flow" />
- <Link href="/render" />
- <Link href="/redirect" />
